<template>
  <div class="chatWrap">
    <div class="MessageBox">
      <div id="MessageBox">
        <div
          class="singleMesssage"
          :key="index"
          v-for="(item, index) in messages"
        >
          <div
            v-if='userName===item.userName'
            class="selfMessage"
          >
            <div class="row-direction">
              <span class="name">{{ item.userName }}</span>
              <span
                class="mess"
                v-if="item.userMessage"
                v-html="dillText(item.userMessage)"
              ></span>
              <img
                class="mess cursor"
                @click="showBig(item.userPic)"
                v-if='item.userPic'
                :src="item.userPic"
                style="max-width:150px;max-height:80px"
              />

              <div
                class="mess fileBox row-direction"
                v-if='item.userFile'
              >
                <img
                  class="cursor"
                  v-if="item.userFile.fileType==='doc'||item.userFile.fileType==='docx'"
                  @click="previewFile(item.userFile.previewUrl)"
                  src='https://user-images-1257142679.cos.ap-chengdu.myqcloud.com/42d1a3eee84d15129c1982fa6d10f912.png'
                >
                <img
                  class="cursor"
                  v-else-if="item.userFile.fileType==='xlsx'||item.userFile.fileType==='xlsm'"
                  @click="previewFile(item.userFile.previewUrl)"
                  src='https://user-images-1257142679.cos.ap-chengdu.myqcloud.com/8242ccce3df83e0e63b288b43c8557c4.png'
                >
                <img
                  class="cursor"
                  v-else-if="item.userFile.fileType==='ppt'||item.userFile.fileType==='pptx'"
                  @click="previewFile(item.userFile.previewUrl)"
                  src='https://user-images-1257142679.cos.ap-chengdu.myqcloud.com/6fa45852fcf7dfbab881b1feaf5a7f6e.png'
                >
                <img
                  class="cursor"
                  v-else-if="item.userFile.fileType==='txt'"
                  @click="previewFile(item.userFile.previewUrl)"
                  src='https://user-images-1257142679.cos.ap-chengdu.myqcloud.com/1d31a86f6a567c31d9a7837a6ac4885a.png'
                >
                <img
                  class="cursor"
                  v-else-if="item.userFile.fileType==='png'||item.userFile.fileType==='jpg'"
                  @click="previewFile(item.userFile.previewUrl)"
                  src='https://user-images-1257142679.cos.ap-chengdu.myqcloud.com/378e910e745b6b3c82094dbe5f2cf163.png'
                >
                <img
                  class="cursor"
                  v-else
                  @click="previewFile(item.userFile.previewUrl)"
                  src='https://user-images-1257142679.cos.ap-chengdu.myqcloud.com/34c9b1dbf4cad88401a1fc34c04c9312.png'
                >

                <div class="downloadButton col-direction">
                  <span
                    class="cursor"
                    style="font-size:12px;color:#ffffff;"
                    @click="previewFile(item.userFile.previewUrl)"
                  >{{item.userFile.fileName}}</span>
                  <div class="buttonBox cursor">
                    <i
                      class="el-icon-download"
                      @click="previewFile(item.userFile.downloadUrl)"
                    ></i>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div
            class="otherMessage"
            v-else
          >
            <div class="row-direction">
              <span class="name">{{ item.userName }}</span>
              <span
                class="mess"
                v-if="item.userMessage"
                v-html="dillText(item.userMessage)"
              ></span>
              <img
                class="mess cursor"
                @click="showBig(item.userPic)"
                v-if='item.userPic'
                :src="item.userPic"
                style="max-width:150px;max-height:80px"
              />
              <div
                class="mess fileBox row-direction"
                v-if='item.userFile'
              >

                <img
                  class="cursor"
                  v-if="item.userFile.fileType==='doc'||item.userFile.fileType==='docx'"
                  @click="previewFile(item.userFile.previewUrl)"
                  src='https://user-images-1257142679.cos.ap-chengdu.myqcloud.com/42d1a3eee84d15129c1982fa6d10f912.png'
                >
                <img
                  class="cursor"
                  v-else-if="item.userFile.fileType==='xlsx'||item.userFile.fileType==='xlsm'"
                  @click="previewFile(item.userFile.previewUrl)"
                  src='https://user-images-1257142679.cos.ap-chengdu.myqcloud.com/8242ccce3df83e0e63b288b43c8557c4.png'
                >
                <img
                  class="cursor"
                  v-else-if="item.userFile.fileType==='ppt'||item.userFile.fileType==='pptx'"
                  @click="previewFile(item.userFile.previewUrl)"
                  src='https://user-images-1257142679.cos.ap-chengdu.myqcloud.com/6fa45852fcf7dfbab881b1feaf5a7f6e.png'
                >
                <img
                  class="cursor"
                  v-else-if="item.userFile.fileType==='txt'"
                  @click="previewFile(item.userFile.previewUrl)"
                  src='https://user-images-1257142679.cos.ap-chengdu.myqcloud.com/1d31a86f6a567c31d9a7837a6ac4885a.png'
                >
                <img
                  class="cursor"
                  v-else-if="item.userFile.fileType==='png'||item.userFile.fileType==='jpg'"
                  @click="previewFile(item.userFile.previewUrl)"
                  src='https://user-images-1257142679.cos.ap-chengdu.myqcloud.com/378e910e745b6b3c82094dbe5f2cf163.png'
                >
                <img
                  class="cursor"
                  v-else
                  @click="previewFile(item.userFile.previewUrl)"
                  src='https://user-images-1257142679.cos.ap-chengdu.myqcloud.com/34c9b1dbf4cad88401a1fc34c04c9312.png'
                >

                <div class="downloadButton col-direction">
                  <span
                    class="cursor"
                    style="font-size:12px;color:#ffffff;"
                    @click="previewFile(item.userFile.previewUrl)"
                  >{{item.userFile.fileName}}</span>
                  <div class="buttonBox cursor">
                    <i
                      class="el-icon-download"
                      @click="previewFile(item.userFile.downloadUrl)"
                    ></i>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <el-progress
        v-if="uploading"
        :percentage="percent"
      ></el-progress>

      <emoji
        v-model="userMessage"
        width="200"
        placement="top"
        @enter="handleSendMessage"
        @click="handleSendMessage"
      >
        <el-upload
          class="upload-demo row-margin"
          action=""
          accept=".png,.jpg,jpeg"
          :http-request="handleUploadPicture"
          :show-file-list='false'
        >
          <el-button
            type="primary"
            icon="el-icon-picture"
            circle
          ></el-button>
        </el-upload>
        <el-upload
          class="upload-demo row-margin"
          action=""
          :before-upload="handleBeforeFileUpload"
          :http-request="handleUploadFile"
          :show-file-list='false'
        >
          <el-button
            type="primary"
            icon="el-icon-folder-add"
            circle
          ></el-button>
        </el-upload>
      </emoji>
      <big-picture
        v-if="showImg"
        :img-src="imgSrc"
        @clickit="viewImg"
      />
    </div>
  </div>
</template>
<script>

import { dillText } from '@/utils/emotion'
// import { apiConference } from '@/api/api'
// import CommonWebSocket from '@/assets/js/commonWebSocket'
import { getSuffix } from '@/utils/file.js'
export default {
  props: {
    messages: {
      type: Array,
      default: () => []
    },
    cid: {
      type: String,
      default: '1287563083105164'
    },
    founderId: {
      type: String,
      default: '1'
    }
  },
  data () {
    return {
      percent: 0,
      uploading: false,
      percentPic: 0,
      uploadingPic: false,
      fromuser: '',
      imgSrc: '',
      showImg: false,
      userMessage: '',
      ws: null,
      groupId: '',
      // filePreviewUrl: apiConference.imUserUpload,
      userId: window.sessionStorage.userId,
      userName: window.sessionStorage.userName,
      dillText
    }
  },
  mounted () {
    this.handleGetGroup()
  },
  methods: {
    // 获取group_id
    handleGetGroup () {
      // this.$request.im.newGroup(this.cid, (res) => {
      //   this.groupId = res.data.group_id
      //   this.connect()
      // })
    },
    // 连接websocket
    connect () {
      // const websocket = new CommonWebSocket(
      //   `${process.env.VUE_APP_WS_BASE_URL_IM}?username=${this.userName}&group_id=${this.groupId}`,
      //   null,
      //   (res) => {
      //     this.handleWebsocketMessage(res)
      //   },
      //   () => {
      //     this.ws = null
      //   },
      //   null,
      //   '{"cmd":13,"hbbyte":"-127"}'
      // )
      // this.ws = websocket.socket
    },
    // 处理websocket消息
    handleWebsocketMessage (message) {
      const { command, data } = message
      console.log(message)
      switch (command) {
        case 11:
          this.handleMessage(data)
          break
        default:
          break
      }
    },
    // 文件消息格式化
    handleFileMessageToObject (message) {
      const obj = JSON.parse(message)
      for (const key in obj) {
        obj[key] = unescape(obj[key])
      }
      obj.fileType = getSuffix(obj.fileName, 1)
      return obj
    },
    // 处理聊天消息
    handleMessage (message) {
      const { msgType, fromUserName, content } = message
      switch (msgType) {
        case 0:
          this.messages.push({
            userName: fromUserName,
            userMessage: content
          })
          break
        case 1:
          this.percent = 100
          this.uploading = false
          this.messages.push({
            userName: fromUserName,
            userPic: content
          })
          break
        case 2:
          this.percent = 100
          this.uploading = false
          this.messages.push({
            userName: fromUserName,
            userFile: this.handleFileMessageToObject(content)
          })
          break
        default:
          break
      }
    },
    // 生成消息
    generageMessage (msgType, content) {
      const msg = {
        from: this.userId,
        fromUserName: this.userName,
        createTime: new Date().getTime(),
        cmd: 11,
        group_id: this.groupId,
        chatType: 1,
        msgType: msgType,
        content: content
      }
      return JSON.stringify(msg)
    },
    // 发送消息
    handleSendMessage () {
      const content = this.userMessage
      // 空消息不能发送
      if (content === '' || content[0] === '') {
        return
      }
      this.ws.send(this.generageMessage(0, content))
      this.userMessage = ''
    },
    // 图片上传
    handleUploadPicture (params) {
      this.uploading = true
      this.percent = 0
      // 假进度条
      let step = 9
      let status = false
      var timerPic = setInterval(() => {
        this.percent = this.percent + step
        if (step > 1 && status) {
          step -= 1
        }
        status = !status
        if (this.percent >= 99) {
          clearInterval(timerPic)
        }
      }, 200)
      // const file = params.file
      // uploadFile(file, this.userId)
      //   .then(res => {
      //     this.handleSendPicture(`https://${res.Location}`)
      //   })
      //   .finally(() => {
      //     this.uploading = false
      //   })
    },
    // 发送图片
    handleSendPicture (url) {
      this.ws.send(this.generageMessage(1, url))
    },
    // 文件上传前的校验
    handleBeforeFileUpload (file) {
      const isLt500M = file.size / 1024 / 1024 < 50
      if (!isLt500M) {
        this.$message.error('上传文件大小不能超过 50MB!')
      }
      return isLt500M
    },
    // 文件上传
    handleUploadFile (params) {
      this.uploading = true
      this.percent = 0
      const formData = new FormData()
      formData.append('file', params.file)
      // 假进度条
      let step = 9
      let status = false
      var timer = setInterval(() => {
        this.percent = this.percent + step
        if (step > 1 && status) {
          step -= 1
        }
        status = !status
        if (this.percent >= 99) {
          clearInterval(timer)
        }
      }, 200)
      this.$request.conference.imUserUpload(
        formData,
        this.cid,
        (res) => {
          this.uploading = false
          this.handleSendFile(res.data)
        },
        () => {
          this.uploading = false
          this.percent = 90
        }
      )
    },
    // 发送文件
    handleSendFile (params) {
      const content = JSON.stringify(params)
      this.ws.send(this.generageMessage(2, content))
    },
    // 打开新窗口预览文件
    previewFile (url) {
      window.open(url)
    },
    // 预览图片
    showBig (pic) {
      this.showImg = true
      this.imgSrc = pic
    },
    // 关闭预览
    viewImg () {
      this.showImg = false
    }
  }
}
</script>
<style lang="scss" scoped>
$bg-color: #1f1f1e;
$font-color: #c9cac9;
$button-color: #2953ff;
::-webkit-scrollbar {
  width: 5px;
}

/*定义滚动条轨道 内阴影+圆角*/

::-webkit-scrollbar-track {
  border-radius: 10px;

  background-color: rgba(0, 0, 0, 0.1);
}

/*定义滑块 内阴影+圆角*/

::-webkit-scrollbar-thumb {
  border-radius: 10px;
  box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
  background-color: rgba(0, 0, 0, 0.1);
}
.cursor {
  cursor: pointer;
}
.row-margin {
  margin-left: 10px;
}
.center {
  display: flex;
  align-items: center;
}
.row-direction {
  display: flex;
  flex-direction: row;
}
.chatWrap {
  height: 100%;
  width: 100%;
  position: relative;
  overflow-x: hidden;
  overflow-y: auto;
}
.MessageBox {
  position: absolute;
  bottom: 0px;
  max-height: 100%;
  overflow-y: auto;
  width: 100%;
  display: flex;
  flex-direction: column;
  #MessageBox {
    overflow-y: auto;
    overflow-x: hidden;
  }
  .singleMesssage {
    margin: 10px 0;
    border-radius: 3px;
    width: 100%;
    .fileBox {
      padding: 10px;
      width: 200px;
      > img {
        width: 40px;
        height: 40px;
      }
      .downloadButton {
        width: 140px;
        display: flex;
        flex-direction: column;
        justify-content: flex-end;
        span {
          margin: 5px 10px 0;
          display: flex;
          flex-wrap: wrap;
        }
        .buttonBox {
          margin-top: 10px;
          display: flex;
          justify-content: flex-end;
          > button {
            display: flex;
            justify-content: center;
            align-items: center;
            padding-top: -7px;
          }
        }
      }
    }
    .selfMessage {
      width: 100%;
      display: flex;
      align-items: flex-end;
      > div {
        width: 100%;
        display: flex;
        flex-direction: row-reverse;
        .mess {
          /*为了给after伪元素自动继承*/
          margin-right: 10px;
          line-height: 18px;
          box-sizing: border-box;
          border-radius: 6px;
          position: relative;
          word-break: break-all;
        }
        /** 通过对小正方形旋转45度解决 **/
        .mess::before {
          content: '';
          position: absolute;
          top: 10px;
          right: -5px;
          width: 10px;
          height: 10px;
          margin-top: -5px;
          background: inherit;
          /*自动继承父元素的背景*/
          transform: rotate(45deg);
        }
      }
    }
    .otherMessage {
      width: 100%;
      display: flex;
      align-items: flex-start;
      > div {
        width: 100%;
        width: fit-content;
        /** 通过对小正方形旋转45度解决 **/
        .mess::before {
          content: '';
          position: absolute;
          top: 10px;
          left: -5px;
          width: 10px;
          height: 10px;
          margin-top: -5px;
          background: inherit;
          /*自动继承父元素的背景*/
          transform: rotate(45deg);
        }
      }
    }
    .name {
      max-width: 80px;
      padding: 5px;
      display: flex;
      height: fit-content;
      align-items: flex-start;
      background-color: #000;
      color: #e6a23c;
    }
    .mess {
      max-width: 200px;
      background-color: #000;
      color: #e6a23c;
      padding: 5px 10px;
      border-bottom-color: #000000;
      /*为了给after伪元素自动继承*/
      margin-left: 10px;
      line-height: 18px;
      box-sizing: border-box;
      border-radius: 6px;
      position: relative;
      word-break: break-all;
    }
  }
}
.inputIcon > img,
.showIcon img {
  cursor: pointer;
  height: 25px;
  width: 25px;
  margin: 5px 0;
}

@media screen and (max-width: 6000px) and (min-width: 1601px) {
  .chatWrap {
    font-size: 16px;
  }
}

@media screen and (max-width: 1600px) and (min-width: 1401px) {
  .chatWrap {
    font-size: 12px;
  }
}
</style>
